package com.xzt.security.config;

import com.xzt.security.filter.JwtAuthenticationFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
public class SecurityConfig {

    @Autowired
    private JwtAuthenticationFilter jwtAuthenticationFilter;

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http.csrf(csrf -> csrf.disable()) // 推荐在测试和 API 项目中先禁用 CSRF
                .authorizeHttpRequests(auth -> auth
                        // 放行注册接口，允许所有用户（包括未登录的）访问
                        .requestMatchers("/api/auth/register", "/api/auth/login").permitAll()

                        // 其它所有接口目前默认都要求认证（后续你可以按需放行或保护）
                        .anyRequest().authenticated()
                )
                // 添加 JWT 过滤器，在 UsernamePasswordAuthenticationFilter 之前执行
                .addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);

        return http.build();
    }
}